/**
 * @Author Sunliangliang 2018/11/16 20:05
 * @Description 
 * @params fileName 导出的excel表格的名称
 * @params el 需要导出到excel表格的表格对象
 */
function exportEXCEL(fileName, el){	
	var docData = [];
	docData.push('<table><thead>');
	// Header
	$hrows = $(el).find('thead').first().find('tr');
	
	$hrows.each(function () {
		docData.push('<tr>' + this.innerHTML + '</tr>');
	});
	docData.push('</thead><tbody>');
 
	// Row Vs Column
	$rows = $(el).find('tbody').first().find('tr');
	$rows.each(function () {
		docData.push('<tr>' + this.innerHTML + '</tr>'); 
	});
	
	// docData.push( '<tr><td></td></tr><tr><td></td></tr><tr><td>' + parseString($('<p>myTableName</p>')) + '</td></tr>');
	docData.push('</tbody></table>');
	
	var docFile = [];
	docFile.push('<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">');
	docFile.push('<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">');
	docFile.push("<head>");
	docFile.push("<!--[if gte mso 9]>" );
	docFile.push("<xml>"                 );
	docFile.push("<x:ExcelWorkbook>"     );
	docFile.push("<x:ExcelWorksheets>" );
	docFile.push("<x:ExcelWorksheet>"    );
	docFile.push("<x:Name>"              );
	docFile.push("xlsWorksheetName");
	docFile.push("</x:Name>"             );
	docFile.push("<x:WorksheetOptions>"  );
	docFile.push("<x:DisplayGridlines/>" );
	docFile.push("</x:WorksheetOptions>" );
	docFile.push("</x:ExcelWorksheet>" );
	docFile.push("</x:ExcelWorksheets>"  );
	docFile.push("</x:ExcelWorkbook>"    );
	docFile.push("</xml>"                );
	docFile.push("<![endif]-->"        );
	docFile.push( "</head>");
	docFile.push( "<body>");
	docFile.push(docData.join(''));
	docFile.push( "</body>");
	docFile.push( "</html>");
	console.log(docFile);
	try {
		var blob = new Blob(docFile,{type: 'application/vnd.ms-excel'});
		saveAs(blob,  fileName+ '.xls');
	} catch (e) {
		downloadFile(fileName + '.xls' ,
				   'data:application/vnd.ms-excel;base64,',
				   docFile.join(''));
	}
}

		
function parseString(cell) {
	var result = '';

	if (cell != null) {
		var $cell = $(cell);
		var htmlData = $cell.html();

		var text = htmlData.replace(/\n/g,'\u2028').replace(/<br\s*[\/]?>/gi, '\u2060');
		var obj = $('<div/>').html(text).contents();
		text = '';
		$.each(obj.text().split("\u2028"), function(i, v) {
			if (i > 0)
				text += " ";
			text += $.trim(v);
		});

		$.each(text.split("\u2060"), function(i, v) {
			if (i > 0)
				result += "\n";
			result += $.trim(v).replace(/\u00AD/g, ""); // remove soft hyphens
		});
	}
	return result;
}

function base64encode(input) {
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = "";
	var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	var i = 0;
	input = utf8Encode(input);
	while (i < input.length) {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);
		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;
		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}
		output = output +
			  keyStr.charAt(enc1) + keyStr.charAt(enc2) +
			  keyStr.charAt(enc3) + keyStr.charAt(enc4);
	}
	return output;
}

function saveAs(blob, filename) {
			
	var type = blob.type;
	var force_saveable_type = 'application/octet-stream';
	if (type && type != force_saveable_type) { // 强制下载，而非在浏览器中打开
		var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
		blob = slice.call(blob, 0, blob.size, force_saveable_type);
	}

	var url = URL.createObjectURL(blob);
	var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
	save_link.href = url;
	save_link.download = filename;

	var event = document.createEvent('MouseEvents');
	event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	save_link.dispatchEvent(event);
	URL.revokeObjectURL(url);
}


function downloadFile(filename, header, data) {
 
	var ua = window.navigator.userAgent;
	if (ua.indexOf("MSIE ") > 0 || !!ua.match(/Trident.*rv\:11\./)) {
		// Internet Explorer (<= 9) workaround by Darryl (https://github.com/dawiong/tableExport.jquery.plugin)
		// based on sampopes answer on http://stackoverflow.com/questions/22317951
		// ! Not working for json and pdf format !
		var frame = document.createElement("iframe");
		if (frame) {
			document.body.appendChild(frame);
			frame.setAttribute("style", "display:none");
			frame.contentDocument.open("txt/html", "replace");
			frame.contentDocument.write(data);
			frame.contentDocument.close();
			frame.focus();
			frame.contentDocument.execCommand("SaveAs", true, filename);
			document.body.removeChild(frame);
		}
	} else {
		var DownloadLink = document.createElement('a');
		if (DownloadLink) {
			DownloadLink.style.display = 'none';
			DownloadLink.download = filename;

			if (header.toLowerCase().indexOf("base64,") >= 0){
				DownloadLink.href = header + base64encode(data);
			} else { 
				DownloadLink.href = encodeURIComponent(header + data);
			}

			document.body.appendChild(DownloadLink);

			if (document.createEvent) {
				if (DownloadEvt == null){
					DownloadEvt = document.createEvent('MouseEvents');
				}
				DownloadEvt.initEvent('click', true, false);
				DownloadLink.dispatchEvent(DownloadEvt);
			} else if (document.createEventObject){
				DownloadLink.fireEvent('onclick');
			} else if (typeof DownloadLink.onclick == 'function'){
				DownloadLink.onclick();
			}
		}
	}
}